package com.eatme.leetcode.lcof;

import java.util.Collections;
import java.util.PriorityQueue;

/**
 * top k
 */
public class Solution40V3 {
    public int[] getLeastNumbers(int[] arr, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
        for (int i = 0; i < k; i++)
            priorityQueue.add(arr[i]);
        for (int i = k; i < arr.length; i++)
            if (!priorityQueue.isEmpty() && arr[i] < priorityQueue.peek()) {
                priorityQueue.remove();
                priorityQueue.add(arr[i]);
            }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = priorityQueue.remove();
        }
        return res;
    }
}